package cn.yeyiu.netonlinevideo.parser.video;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.yeyiu.netonlinevideo.bean.SourceData;
import cn.yeyiu.netonlinevideo.bean.TypeData;
import cn.yeyiu.netonlinevideo.parser.Parser;
import cn.yeyiu.netonlinevideo.viewmodel.DataListViewModel;
import cn.yeyiu.util.NetUtil;
import cn.yeyiu.util.bean.MediaData;
import cn.yeyiu.util.bean.VideoInfo;


/**
 * json
 */
public class XJ1Parser extends Parser {


    public XJ1Parser(SourceData source) {
        super(source);
    }

    @Override
    public Object getBaseData(String type, int pageIndex) {
        String vtype = getArgv(type, "vtype");
        String json = NetUtil.getByUrl(source.url + "/vod/" + vtype + "-0-0-0-0-0-0-0-0-0-" + pageIndex + 1);
        return JSONObject.parseObject(json);
    }

    @Override
    public List<MediaData> getDataList(Object data, String type) {
        JSONObject jo = (JSONObject) data;
        JSONArray jsonArray = jo.getJSONObject("data").getJSONArray("vodrows");

        List<MediaData> videoInfos = new ArrayList<>();
        MediaData mediaData;
        VideoInfo videoInfo;
        for (int i = 0; i < jsonArray.size(); ++i) {
            videoInfo = new VideoInfo();
            mediaData = new MediaData();

            videoInfo.code = source.code;
            videoInfo.type = type;
            videoInfo.title = jsonArray.getJSONObject(i).getString("title");
            videoInfo.picSrc = jsonArray.getJSONObject(i).getString("coverpic");
            // pre url
            videoInfo.videoSrc = source.url + jsonArray.getJSONObject(i).getString("play_url");

            mediaData.wrap(videoInfo);
            videoInfos.add(mediaData);

        }
        return videoInfos;
    }

    @Override
    public Object buildData(MediaData mediaData) {
        // get rel url
        VideoInfo videoInfo = (VideoInfo) mediaData.data;
        JSONObject result = JSONObject.parseObject(NetUtil.getByUrl(videoInfo.videoSrc));

        videoInfo.info = result.getString("errmsg");

        JSONObject jsonObject = result.getJSONObject("data");
        String url = jsonObject.getString("httpurl");
        if (url == null || "".equals(url)) {
            url = jsonObject.getString("httpurl_preview");
            if (url == null | "".equals(url)) {
                return "";
            }
            int last = url.lastIndexOf("m3u8");
            url = url.substring(0, last) + "m3u8";
        }
        videoInfo.videoSrc = url;

        return videoInfo;
    }
}
